package cn.onesdream.app.api.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@SpringBootApplication(scanBasePackages = "cn.onesdream.app")
public class AppWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.secret}")
    private String secret;

    @Autowired
    private AppUserDetailsServiceImpl appUserDetailsServiceImpl;

    @Autowired
    private TokenAuthenticationFilter tokenAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
        禁用session保持登陆状态
         */
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        http.formLogin().loginPage("/api/app/user/loginFailure")
                .failureForwardUrl("/api/app/user/loginFailure")
                .successForwardUrl("/api/app/user/loginSuccess").and()
                .authorizeRequests().antMatchers(
                        "/templates/**",
                "/resources/**",
                "/login",
                "/api/app/user/loginByPassword",
                "/api/app/user/loginFailure",
                "/api/app/user/loginSuccess",
                "/api/app/user/loginByPhoneCode",
//                "/api/app/user/chat",
//                "/websocket",
                "/v2/**",
                "/swagger-resources",
                "/swagger-resources/**",
                "/configuration/ui",
                "/configuration/security",
                "/swagger-ui.html/**",
                "/doc.html/**",
                "/webjars/**",
                "/druid/**",
//                "/api/article/",
//                "/api/article/**",
                "/static/**").permitAll().anyRequest().authenticated().and()
                .csrf().disable();

    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(appUserDetailsServiceImpl).passwordEncoder(encoder);
    }

}
